package com.example.designpattern;

import android.graphics.Bitmap;

import androidx.annotation.NonNull;
import androidx.collection.LruCache;

/**
 * Author 方隽琦
 * Date 2020/12/28
 * Description
 */
public class MemoryCache implements ImageCache {
    private LruCache<String,Bitmap> mMemoryCache;
    public MemoryCache(){
        //初始化LRU缓存
        final int maxMemory = (int) (Runtime.getRuntime().maxMemory() /1024);
        //取四分之一的可用内存作为缓存
        final int cacheSize = maxMemory / 4;
        mMemoryCache = new LruCache<String, Bitmap>(cacheSize){
            @Override
            protected int sizeOf(@NonNull String key, @NonNull Bitmap value) {
                return value.getRowBytes() * value.getHeight() /1024;
            }
        };
    }

    @Override
    public Bitmap get(String url) {
        return mMemoryCache.get(url);
    }

    @Override
    public void put(String url, Bitmap bitmap) {
        mMemoryCache.put(url,bitmap);
    }
}
